package co.baiku.boot.core.web.controller;

import co.baiku.boot.common.tools.IpTools;
import co.baiku.boot.common.tools.JsonTools;
import co.baiku.boot.common.tools.StringTools;
import co.baiku.boot.common.tools.ZipTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;
import java.util.zip.ZipOutputStream;

public class BaseController {
    private Logger log = LoggerFactory.getLogger(BaseController.class);

    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public HttpSession getSession() {
        return getRequest().getSession();
    }

    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public Map<String, String[]> getParameterMap() {
        return getRequest().getParameterMap();
    }

    public String getClientAddress() {
        return IpTools.getIpAddr(getRequest());
    }

    public void setCharacterEncoding(String characterEncoding) {
        HttpServletRequest request = getRequest();
        try {
            request.setCharacterEncoding(characterEncoding);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
    }

    public <T> T getParam(String key, T defaultValue) {
        HttpServletRequest request = getRequest();
        Object value = request.getParameter(key);
        if (value == null) {
            return defaultValue;
        }
        String val = value.toString();
        return StringTools.coverTo(val, defaultValue);
    }

    public <T> T getAttr(String key, T defaultValue) {
        HttpServletRequest request = getRequest();
        Object value = request.getAttribute(key);
        if (value == null) {
            return defaultValue;
        }
        String val = value.toString();
        return StringTools.coverTo(val, defaultValue);
    }

    public <T> T getSessionAttr(String key) {
        if (key != null) {
            return (T) getSession().getAttribute(key);
        }
        return null;
    }

    public void setSessionAttr(String key, Object val) {
        if (key != null && val != null) {
            getSession().setAttribute(key, val);
        }
    }

    public void outJson(Object msg) throws IOException {
        out(JsonTools.beanToJson(msg), "application/json; charset=utf-8");
    }

    public void outString(String str) throws IOException {
        out(str, "html/plain;charset=utf-8");
    }

    public void outHtml(String str) throws IOException {
        out(str, "html/text;charset=utf-8");
    }


    public void out(Object msg, String contentType) throws IOException {
        HttpServletResponse response = getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        PrintWriter writer = response.getWriter();
        writer.print(msg);
        writer.flush();
        writer.close();
    }

    public void outZip(String filename, File... files) throws IOException {
        //预处理
        HttpServletResponse response = getResponse();
        OutputStream res = response.getOutputStream();
        // 清空输出流(在迅雷下载不会出现一长窜)
        getResponse().reset();
        // 设定输出文件头
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("application/zip");
        //写文件
        ZipOutputStream zos = new ZipOutputStream(res);
        ZipTools.write(zos, files);
        //关闭资源
        zos.close();
        res.flush();
        res.close();
    }

    public void outImage(BufferedImage buffImg, String imageExt) {
        ServletOutputStream sos = null;
        try {
            sos = getResponse().getOutputStream();
            ImageIO.write(buffImg, imageExt, sos);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (sos != null) {
                    sos.flush();
                    sos.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 获取requestbody
     *
     * @param request
     * @return
     * @throws IOException
     */
    public String requestBody(HttpServletRequest request) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StringTools.UTF8));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }


}
